<?php


namespace app\user\controller;


use app\admin\model\AccountStatus;
use app\common\model\MiniApp as MiniAppModel;
use app\user\controller\Index;
use app\user\logic\ShareLinkLogic;
use app\user\model\TtUser;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Article;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Request;
use app\common\model\Movie as MovieModel;
use think\facade\Validate;
use app\common\model\Setting;

use app\common\model\WechatShareLink as WechatShareLinkModel;

class Video extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkTTUserToken::class',
        // 'app\http\middleware\checkUserAuth::class',
    ];


    //创建完整视频的链接
    public function create()
    {

        $video_url=Request::param('video_url');     //视频的链接地址
        $url_mode = Request::param('url_mode',1); //1文件，2腾讯视频地址
        $user_id = Request::param('user_id');
        $setting = Setting::getAllSetting();      //获取平台的设置
        $title = $setting['video_share_title'];      //获取平台的设置
        //  $user=\app\user\model\User::get($user_id);
        //  dump(Request::param("user_id"));
        if(!ShareLinkLogic::checkMaxLink($user_id)){
            $this->result(0,400,'今天生成的链接数已经达到了最大值');
        }

        //微信小程序的信息
        $mini_app = MiniAppModel::where('id', '2')->find();

        //获取数据库公众号，配置文件
        //$config = Config::get('miniprogram.officialAccount');
        $config = ShareLinkLogic::getAccount();
        $app = Factory::officialAccount($config);
        $no=rand(20000000,99999999). time();
       
        // //跳转的链接
        $path="pages/movie/index?promote_user_id=$user_id&mini_app_code=movie&no=$no";

        // // 上传单篇图文
        $article = new Article([
            'title' => $title,
            'thumb_media_id' => ShareLinkLogic::getCoverMediaId(),
            'show_cover' => 0, // 是否在文章内容显示封面图片
            "content_source_url" => ShareLinkLogic::getContentSourceUrl(),
            'content' => ShareLinkLogic::getVideoArticleContent($mini_app,$path,$user_id),
        ]);

            try{
                $res3 = $app->material->uploadArticle($article);
                 
                $res= $app->broadcasting->sendNews($res3->media_id,ShareLinkLogic::getPushOpenids());
               
        //         //超出公众号最大限制
                if ($res->errcode == 45009) {
                    $account_id = AccountStatus::where([
                        ['app_id', '=', $config['app_id']],
                        ['add_time', 'BETWEEN', today()]
                    ])->find();
                    if (empty($account_id)) {
                        $account = new AccountStatus();
                        $account->app_id = $config['app_id'];
                        $account->status = 0;
                        $account->add_time = time();
                        $re = $account->save();
                    }
                    //清除缓存
                    Cache::rm('cover_media_id');
                    Cache::rm('test_cover_url');
                    Cache::rm('openids');
                    Cache::rm('cover_url');
                    Cache::rm('test_cover_url');
                    $this->result(0, 400, '生成链接超出最大值，请重试');
                }
            }catch (Exception $e){
                //清除缓存
                Cache::rm('cover_media_id');
                Cache::rm('test_cover_url');
                Cache::rm('openids');
                Cache::rm('cover_url');
                Cache::rm('test_cover_url');
            }

        try{
            $msg_id=$res->msg_id ;
        }catch (Exception $e){
            $this->result($e->getMessage(),400,'生成失败');
        }
        $data = [
            'user_id'=>$user_id,
            'app_id'=>$config['app_id'],
            'created_id'=>$user_id,
            'no'=>$no,
            'mini_app_code'=>'movie',
            "product_id"=>0,
            'title'=>$title,
            'msg_id'=> $msg_id,
            "url" => '',
            "url_mode" => $url_mode,
            "video_url" => $video_url,
            'add_time'=>time()
        ];
        //存数据库
        $res2=WechatShareLinkModel::create( $data);

        //轮询60秒，60秒还没生成成功，直接删掉，重新生成
        for ($i = 0; $i < 41; $i++) {
            sleep(1);
            $link = WechatShareLinkModel::where('msg_id', $msg_id)->find();
            if ($link && $link->url != '') {
                //return $link;
                $this->result($link, 200, '生成成功');
            }
        }
        //链接生成失败了,删除视频
        $res= WechatShareLinkModel::where([
            ['msg_id','=',$msg_id]   ,
        ])->update([
            'user_id'=>0,
            'video_url'=>0
        ]);
        $this->result('',400,'链接生成超时');
    }

    //指定用户的电影列表
    public function index()
    {
        $user_id= Request::param('user_id');
        $page=Request::param('page',1);
        $list=  WechatShareLinkModel::where([
            ['user_id','=',$user_id]   ,
            ['mini_app_code','=','movie']   ,
        ] )->page($page,20)->order('id','desc')->select();
        $this->result($list,200,'成功');
    }

    //指定用户的电影列表
    public function delete()
    {
        $url_id= Request::param('url_id');
        $user_id= Request::param('user_id');
        $res= WechatShareLinkModel::where([
            ['user_id','=',$user_id]   ,
            ['id','=',$url_id]   ,
        ])->update([
            'user_id'=>0,
            'video_url'=>0
        ]);
        $this->result($res,200,'成功');
    }

}
